package com.example.pay_service.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeRefundModel;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.example.pay_service.config.AlipayConfig;
import com.example.pay_service.vo.RefundPojo;
import net.sf.json.JSON;
import net.sf.json.JSONObject;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @title: Refund
 * @projectName mall
 * @description: TODO
 * @author TLJ
 * @date 2021/12/128:33
 */

@RestController
@RequestMapping("pay")
public class Refund {

    @RequestMapping("refund")
    public Object  refunds(RefundPojo pojo) throws AlipayApiException {
        System.out.println(11111);
        System.out.println(pojo.getTrade_no());
        System.out.println(pojo.getOut_trade_no());
        System.out.println(pojo.getOut_request_no());
        System.out.println(pojo.getRefund_amount());
        System.out.println(pojo.getRefund_reason());
        if(pojo.getTrade_no()!=null||pojo.getOut_trade_no()!=null){
            //商户订单号和支付宝交易号不能同时为空。 trade_no、  out_trade_no如果同时存在优先取trade_no
            //商户订单号，和支付宝交易号二选一
            String out_trade_no = pojo.getOut_trade_no();
            //支付宝交易号，和商户订单号二选一
            String trade_no =pojo.getTrade_no();
            //退款金额，不能大于订单总金额
            String refund_amount=pojo.getRefund_amount();
            //退款的原因说明
            String refund_reason=pojo.getRefund_reason();
            //标识一次退款请求，同一笔交易多次退款需要保证唯一，如需部分退款，则此参数必传。
            String  out_request_no=pojo.getOut_request_no();
            /**********************/
            // SDK 公共请求类，包含公共请求参数，以及封装了签名与验签，开发者无需关注签名与验签
            AlipayClient client = new DefaultAlipayClient(AlipayConfig.URL, AlipayConfig.APPID, AlipayConfig.RSA_PRIVATE_KEY, AlipayConfig.FORMAT, AlipayConfig.CHARSET, AlipayConfig.ALIPAY_PUBLIC_KEY,AlipayConfig.SIGNTYPE);
            AlipayTradeRefundRequest alipay_request = new AlipayTradeRefundRequest();

            AlipayTradeRefundModel model=new AlipayTradeRefundModel();
            model.setOutTradeNo(out_trade_no);
            model.setTradeNo(trade_no);
            model.setRefundAmount(refund_amount);
            model.setRefundReason(refund_reason);
            model.setOutRequestNo(out_request_no);
            alipay_request.setBizModel(model);

            AlipayTradeRefundResponse alipay_response =client.execute(alipay_request);
            //System.out.println();

            System.out.println(alipay_response.getCode());
            System.out.println(alipay_response.getOutTradeNo());
            return JSONObject.fromObject(alipay_response.getBody());


        }
        return null;
    }

}
